package builder;

/**
 * 建造者模式的一个简单的实现
 * 将 Builder 类作为用户类 User 的一个静态内部类。将产品类、抽象建造者和具体建造者融合在一起。
 *
 * @author Liu Yicong
 * @date 2025/9/21
 */
public class User {
	// 必选字段 (final，保证不可变性)
	private final String firstName;
	private final String lastName;

	// 可选字段
	private final int age;
	private final String phone;
	private final String address;

	// 核心 1: 私有化构造函数，只能通过 Builder 访问
	private User(Builder builder) {
		this.firstName = builder.firstName;
		this.lastName = builder.lastName;
		this.age = builder.age;
		this.phone = builder.phone;
		this.address = builder.address;
	}


	// 核心 2: 静态内部 Builder 类
	public static class Builder {
		// 必选字段必须在 Builder 构造函数中初始化
		private final String firstName;
		private final String lastName;

		// 可选字段 (使用默认值)
		private int age = 0;
		private String phone = "N/A";
		private String address = "N/A";

		// Builder 的构造函数只接收必填参数
		public Builder(String firstName, String lastName) {
			this.firstName = firstName;
			this.lastName = lastName;
		}

		// 核心 3: 链式调用设置可选参数
		public Builder age(int age) {
			this.age = age;
			return this; // 返回 Builder 自身，实现链式调用
		}

		public Builder phone(String phone) {
			this.phone = phone;
			return this;
		}

		// 核心 4: build() 方法，返回最终构造的产品对象
		public User build() {
			// 可在此处进行最终的合法性检查
			if (this.age < 0) {
				throw new IllegalStateException("年龄不能为负数");
			}
			return new User(this);
		}
	}

	@Override
	public String toString() {
		return "User{" +
				"firstName='" + firstName + '\'' +
				", lastName='" + lastName + '\'' +
				", age=" + age +
				", phone='" + phone + '\'' +
				", address='" + address + '\'' +
				'}';
	}
}
